from django import forms
from web import models
from web.forms.bootstrap import BootstrapForm
from django.core.exceptions import ValidationError
from utils.tencent.cos import check_file
class FolderModelForm(forms.ModelForm):
    name=forms.CharField(label='文件夹',widget=forms.TextInput(attrs={'placeholder':'请输入文件夹'}))
    def __init__(self,request,parent_object,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request=request
        self.parent_object=parent_object
    class Meta:
        model=models.FileRepository
        fields=['name',]
        # widgets={
        #     'name':forms.TextInput(attrs={'placeholder':'请输入文件夹'})
        # }
    def clean_name(self):
        name=self.cleaned_data.get('name')
        queryset=models.FileRepository.objects.filter(file_type=2,name=name,project=self.request.tracer.project)
        if self.parent_object:
            exists=queryset.filter(parent=self.parent_object).exists()
        else:
            exists = queryset.filter(parent__isnull=True).exists()
        if exists:
            # self.add_error('name','该文件夹已经存在，请换个名字')
            raise ValidationError('该文件夹已经存在')
        return name

class FileModelForm(forms.ModelForm):
    '''
    上传成功后  把文件的元数据写入数据库中 需要的 信息

    '''
    etag=forms.CharField(label='Etag')
    class Meta:
        model=models.FileRepository
        exclude=['project','file_type','update_user','update_datetime',]
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request=request
    def clean_file_path(self):
        return 'https://{}'.format(self.cleaned_data.get('file_path'))

    def clean(self):
        etag=self.cleaned_data.get('etag')
        key=self.cleaned_data.get('key')
        size=self.cleaned_data.get('size')
        if not key or not etag:
            return self.cleaned_data
        from qcloud_cos.cos_exception import CosServiceError
        try:
            result=check_file(self.request.tracer.project.bucket,self.request.tracer.project.region,key)
        except CosServiceError as e:
            self.add_error('key','文件不存在')
        cos_etag = result.get('ETag')
        if cos_etag!=etag:
            self.add_error('etag','ETag错误')

        return self.cleaned_data